package com.example.demo

import android.content.Context
import android.os.Build
import android.support.annotation.RequiresApi
import android.util.AttributeSet
import android.view.Gravity
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.ScrollView
import android.widget.TextView

class WheelView: ScrollView {
    constructor(context: Context?) : super(context){
        initView(context,null)
    }
    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs){
        initView(context,attrs)
    }
    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr){
        initView(context,attrs)
    }
    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int) : super(
        context,
        attrs,
        defStyleAttr,
        defStyleRes
    ){
        initView(context,attrs)
    }

    private val mList = ArrayList<String>()
    private lateinit var mLayout: LinearLayout
    private var mVisibleCount = 5
    private var mItemHeight = 90

    private fun initView(context: Context?, attrs: AttributeSet?) {
        mLayout = LinearLayout(context)
        mLayout.orientation = LinearLayout.VERTICAL

        val params = ViewGroup.LayoutParams(LayoutParams.MATCH_PARENT,mItemHeight * mVisibleCount)
        mLayout.layoutParams = params

        removeAllViews()
        addView(mLayout)
        this.layoutParams = params


        for(i in 19..50){
            mList.add("$20$i")
        }

        mLayout.removeAllViews()

        val count = mList.count()
        for (i in 0 until count){

            val itemParams = LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,mItemHeight)
            val textView = TextView(context)
            textView.gravity = Gravity.CENTER
            textView.text = mList[i]
            if(i == 0){
                itemParams.topMargin = mItemHeight * (mVisibleCount / 2 + mVisibleCount % 2 / 2f).toInt()
                itemParams.bottomMargin = 0
            }else if(i == count - 1){
                itemParams.topMargin = 0
                itemParams.bottomMargin = mItemHeight * (mVisibleCount / 2 + mVisibleCount % 2 / 2f).toInt()
            }else{
                itemParams.topMargin = 0
                itemParams.bottomMargin = 0
            }
            textView.layoutParams = itemParams
            mLayout.addView(textView)
        }

    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
    }

}